﻿using Newtonsoft.Json.Linq;
using RestSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using ESMAM.Model;

namespace ESMAM.Tools
{
    public static class FanYinUtil
    {
        public const string TransAppId = "20180903000202054";
        public const string TransAppSecret = "rH5ywtwpZWadr_2LlkY_";


        public static string TransBaseUrl = "https://fanyi-api.baidu.com/api/trans/vip/translate";

        static Random rdom = new Random();
        public static string Trans(string str, Lang to, Lang from = Lang.zh)
        {
            if (string.IsNullOrWhiteSpace(str))
            {
                return str;
            }
            var client = new RestClient(TransBaseUrl);
            var req = new RestRequest(Method.GET);
            req.AddParameter("q", str);
            req.AddParameter("from", from.ToString());
            req.AddParameter("to", to.ToString());
            req.AddParameter("appid", TransAppId);
            string salt = rdom.NextRdomString(10);
            req.AddParameter("salt", salt);
            string strMd5 = (TransAppId + str + salt + TransAppSecret).Md5Hash();
            req.AddParameter("sign", strMd5);

            var resp = client.Execute(req);
            List<string> lstDest = new List<string>();
            try
            {
                JObject obj = JObject.Parse(resp.Content);
                var jArr = obj["trans_result"];
                int len = jArr.Count();
                for (int j = 0; j < len; j++)
                {
                    var jObj = jArr[j] as JObject;
                    lstDest.Add(jObj["dst"].ToString());
                }
                return string.Join("\r\n", lstDest);
            }
            catch (Exception ex)
            {
                Console.WriteLine("翻译出现失败！");
            }
            return str;
        }

        public static string[] Trans(string[] strs, Lang to, Lang from = Lang.zh)
        {
            if (strs == null || strs.Length <= 0)
            {
                return strs;
            }
            string res = Trans(string.Join("\r\n", strs), to, from) ?? string.Empty;
            return res.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
        }

        public static List<string> Trans(List<string> lst, Lang to, Lang from = Lang.zh)
        {
            if (lst == null || lst.Count() <= 0)
            {
                return lst;
            }
            string res = Trans(string.Join("\r\n", lst), to, from) ?? string.Empty;
            return res.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries).ToList();
        }

        /// <summary>
        ///  随机返回 字符串
        /// </summary>
        /// <param name="len">字符长度</param>
        public static string NextRdomString(this Random random, int len)
        {
            string noceStr = string.Empty;
            string strs = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
            for (int i = 0; i < len; i++)
            {
                string r = strs[random.Next(0, strs.Length)].ToString();
                noceStr += r;
            }
            return noceStr;
        }

        /// <summary>
        /// 字符串的Md5值
        /// </summary>
        public static string Md5Hash(this string input)
        {
            if (input == null)
            {
                return null;
            }

            MD5 md5Hash = MD5.Create();
            // 将输入字符串转换为字节数组并计算哈希数据
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
            // 创建一个 Stringbuilder 来收集字节并创建字符串
            StringBuilder sBuilder = new StringBuilder();
            // 循环遍历哈希数据的每一个字节并格式化为十六进制字符串
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }
            // 返回十六进制字符串
            return sBuilder.ToString();
        }
    }
}
